<template>
  <el-card class="form-container" shadow="never">
    <form-detail
      ref="skuInfoDetail"
      v-show="showStatus[0]"
      v-model="skuForm"
      :is-edit="isEdit"
      @nextStep="nextStep"
      @update-sku="handleAddSkuPrice"
      @insertSkuPrice="handleInsertSkuPrice"
      @deleteSkuPrice="handleDeleteSkuPrice"
      @finishCommit="finishCommit"
    >
    </form-detail>
  </el-card>
</template>
<script>
import FormDetail from "./FormDetail.vue";
import { addSku, fetchSkuInfo, updateSku } from "@/api/product";
import { cloneDeep } from "lodash/lang";
import { sortPmsSkuPriceByAge } from "@/utils/pms";
import { formatCentToYuan, formatYuanToCent } from "@/utils/format";

const defaultProductParam = {
  areaId: undefined,
  healthNoticeUrl: "",
  hospitalIds: [],
  pmsSkuPrices: [],
  purchaseLimitNum: 1,
  skuName: "",
};
export default {
  name: "ProductDetail",
  components: {
    FormDetail,
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      active: 0,
      skuForm: Object.assign({}, defaultProductParam),
      showStatus: [true, false, false, false],
    };
  },
  created() {
    if (this.isEdit) {
      fetchSkuInfo(this.$route.query.id).then((response) => {
        const { skuHospitals = [], pmsSkuPrices, ...rest } = response.data;
        const hospitalIds = (skuHospitals || [])
          .filter(
            (item) => item.hospitalId !== null && item.hospitalId !== undefined,
          )
          .map((item) => item.hospitalId);

        this.skuForm = {
          ...rest,
          hospitalIds,
          pmsSkuPrices: sortPmsSkuPriceByAge(
            pmsSkuPrices.map((item) => ({
              ...item,
              price: formatCentToYuan(item.price),
            })),
          ),
        };

        this.$nextTick(() => {
          this.$refs.skuInfoDetail.setInitialData();
        });
      });
    }
  },

  methods: {
    handleAddSkuPrice(skus) {
      if (!skus || !Array.isArray(skus)) {
        console.error("无效的价格数据", skus);
        return;
      }

      // 合并新旧数据
      this.skuForm.pmsSkuPrices = skus.map((newSku) => {
        // 尝试从原有数据中找到匹配项（基于年龄段）
        const existingSku = this.skuForm.pmsSkuPrices.find(
          (oldSku) =>
            oldSku.startPurchaseAge === newSku.startPurchaseAge &&
            oldSku.startUnit === newSku.startUnit &&
            oldSku.endPurchaseAge === newSku.endPurchaseAge &&
            oldSku.endUnit === newSku.endUnit &&
            oldSku.paymentMethod === newSku.paymentMethod,
        );

        // 合并数据
        return {
          ...(existingSku || {}),
          ...newSku,
        };
      });

      console.log(this.skuForm.pmsSkuPrices);
    },
    handleInsertSkuPrice(index) {
      this.skuForm.pmsSkuPrices.splice(
        index,
        0,
        cloneDeep(this.skuForm.pmsSkuPrices[index]),
      );
    },
    handleDeleteSkuPrice(index) {
      this.skuForm.pmsSkuPrices.splice(index, 1);
    },
    hideAll() {
      for (let i = 0; i < this.showStatus.length; i++) {
        this.showStatus[i] = false;
      }
    },
    prevStep() {
      if (this.active > 0 && this.active < this.showStatus.length) {
        this.active--;
        this.hideAll();
        this.showStatus[this.active] = true;
      }
    },
    nextStep() {
      if (this.active < this.showStatus.length - 1) {
        this.active++;
        this.hideAll();
        this.showStatus[this.active] = true;
      }
    },
    finishCommit(isEdit) {
      this.$confirm("是否要提交该产品规格", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const postData = Object.assign({}, this.skuForm, {
          pmsSkuPrices: this.skuForm.pmsSkuPrices.map((item) => ({
            ...item,
            price: formatYuanToCent(item.price),
          })),
        });
        if (isEdit) {
          updateSku(postData).then(() => {
            this.$message({
              type: "success",
              message: "提交成功",
              duration: 1000,
            });
            this.$router.back();
          });
        } else {
          addSku(postData).then(() => {
            this.$message({
              type: "success",
              message: "提交成功",
              duration: 1000,
            });
            this.$router.back();
          });
        }
      });
    },
  },
};
</script>
<style>
.form-container {
  width: 960px;
}
.form-inner-container {
  width: 800px;
}
</style>
